package main.java.com.yc.navy.snacknet.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.yc.navy.snacknet.util.ConstantIfo;

@Controller
@RequestMapping()
public class CreateCodeController {
	@GetMapping("/code")
	public void createCode(HttpSession session, HttpServletResponse response) throws IOException {
		response.setHeader("Pargma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		
		String code = getRandomCode();//生成验证
		session.setAttribute(ConstantIfo.CURRENTLOGINCODE, code);
		
		BufferedImage image = getCodeImage(code, 110, 38);
		ImageIO.write(image, "JPEG", response.getOutputStream());
	}
	
	/**
	 * 生成验证图片
	 * @param code
	 * @param i
	 * @param j
	 * @return
	 */
	private BufferedImage getCodeImage(String code, int w, int h) {
		BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		
		//绘制背景图
		g.setColor(this.getRandomColor(220, 30));	//颜色
		g.fillRect(0, 0, w, h);	//用指定的背景填充图片
		
		//绘制干扰线
		Random rd = new Random();
		int x1, y1, x2, y2;
		for(int i = 0; i < 50; ++i) {
			x1 = rd.nextInt(w);
			y1 = rd.nextInt(h);
			x2 = rd.nextInt(w);
			y2 = rd.nextInt(h);
			g.setColor(getRandomColor(140, 60));
			g.drawLine(x1, y1, x2, y2);
		}
		
		//绘制验证码
		g.setFont(new Font("Courier New", Font.ITALIC, 26));
		char[] codes = code.toCharArray();
		System.out.println(codes);
		for(int i = 0, len = codes.length; i < len; ++ i) {
			g.setColor(getRandomColor(20, 100));
			g.drawString(String.valueOf(codes[i]), 8 + 16 * i, 25);
		}
		g.dispose();
		return image;
	}

	/**
	 * 生成随机颜色
	 * @param start
	 * @param bound
	 * @return
	 */
	private Color getRandomColor(int start, int bound) {
		Random rd = new Random();
		int r = start + rd.nextInt(bound);
		int g = start + rd.nextInt(bound);
		int b = start + rd.nextInt(bound);
		return new Color(r, g, b);
	}

	/**
	 * 生成验证码
	 * @return
	 */
	private String getRandomCode() {
		Random rd = new Random();
		String str = "";
		int flag = 0;
		for(int i = 0; i < 4; ++i) {
			flag = rd.nextInt(3);
			switch(flag) {
			case 0: str += rd.nextInt(10);break;
			case 1: str += (char)(rd.nextInt(26) + 65);break;
			case 2: str += (char)(rd.nextInt(26) + 97);break;
			}
		}
		return str;
	}
}
